<template>
  <div class="gl_contentBox gl_heightFull">
    <!-- 控制按钮 -->
    <div class="gl_searchBox gl_mb_15">
      <el-row>
        <el-col :span="24">
          <el-button type="primary" size="mini" :loading="warningBtnLoading" @click="earlyWarningSetting()">预警设置</el-button>
          <el-button type="primary" size="mini" :loading="downloadLoading" @click="exportFile()">导出</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格 -->
    <el-table v-loading="tableLoading" :data="tableData" size="small" class="gl_table_noBorder gl_mb_15" style="width: 100%">
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="学员姓名" prop="studentName" />
      <el-table-column label="联系方式">
        <template slot-scope="{row}">
          <template v-if="row.studentContacts && row.studentContacts.length">
            <div v-for="(item, index) in row.studentContacts" :key="index">{{ item.contactType.name }} {{ item.phoneNumber }}</div>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="所在班级" prop="className">
        <template slot-scope="{row}">
          <template v-if="row.classes && row.classes.length">
            <div v-for="(item, index) in row.classes" :key="index">{{ item.name }}</div>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="剩余课时" prop="remainClassPeriod" align="center" />
      <el-table-column label="到期时间" prop="expire">
        <template slot-scope="{row}">
          <div>
            {{ row.effectiveDate ? row.effectiveDate.slice(0, 10) : '' }}
            {{ row.effectiveDate ? row.effectiveDate.slice(11, 16) : '' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" @click="clickRenewal(row)">续费</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row style="text-align: right;">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="qo.MaxResultCount"
        :current-page="qo.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>

    <!-- 预警设置 -->
    <el-dialog
      title="预警设置"
      class="gl_dialog_TitleLine gl_dl_footer"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <div class="gl_px_20">
        <div class="gl_mb_15">
          <el-alert title="满足以下条件的学员将进入续费预警列表" type="warning" :closable="false" />
        </div>
        <el-form ref="formBalanceWarningSetting" class="gl_form_mini" size="medium" :model="vo" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="剩余课时 ≤" prop="remainClassPeriod">
                <el-input-number v-model="vo.remainClassPeriod" style="width: 100%" placeholder="请输入课时" :controls="false" :min="0" :max="100000" />
              </el-form-item>
            </el-col>
            <el-col :span="2" align="center">
              <span class="mock_label">或</span>
            </el-col>
            <el-col :span="11">
              <el-form-item label="剩余天数 ≤" prop="remainDay">
                <el-input-number v-model="vo.remainDay" style="width: 100%" placeholder="请输入天数" :controls="false" :min="0" :max="100000" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="submitLoading" size="mini" @click="submitDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  api_GET_ClubBalanceWarningSettingStudentBalanceWarning, // 分页获取续费预警信息
  api_GET_ClubBalanceWarningSetting, // 获取当前道馆的续费预警设置信息
  api_POST_ClubBalanceWarningSetting, // 添加当前道馆的续费预警设置信息
  api_PUT_ClubBalanceWarningSetting // 修改当前道馆的续费预警设置信息
} from '@/extend/api/hallswaggerApi/app.js';

import {
  Api_GET_ClubBalanceWarningSettingStudentBalanceWarningQO,
  BalanceWarningSettingInput
} from '@/lib/form/hall/swaggerForm.js';

import {
  BalanceWarningSettingInput_Rules
} from '@/lib/validate/hall/index.js';

import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';

import { CopyData } from '@/lib';

export default {
  data () {
    return {
      tableLoading: false,
      tableData: [],
      qo: new Api_GET_ClubBalanceWarningSettingStudentBalanceWarningQO(),
      total: 0,
      dialogVisible: false,
      submitLoading: false,
      rules: new BalanceWarningSettingInput_Rules(),
      vo: new BalanceWarningSettingInput(),
      warningData: null,
      warningBtnLoading: false, // 预警设置按钮Loading
      downloadLoading: false
    };
  },
  created () {
    this.getPageList();
    this.getClubBalanceWarningSetting();
  },
  methods: {
    getPageList (page) {
      const _qo = JSON.parse(JSON.stringify(this.qo));
      _qo.Page = page || 1;
      _qo.SkipCount = (_qo.Page - 1) * _qo.MaxResultCount;
      this.apiGetRenewalList(_qo);
    },
    // 获取续费预警列表
    apiGetRenewalList (qo) {
      this.tableLoading = true;
      api_GET_ClubBalanceWarningSettingStudentBalanceWarning(qo)
        .then(
          res => {
            this.tableLoading = false;
            this.total = res.totalCount;
            this.tableData = res.items;
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              message: `列表获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取预警设置信息
    getClubBalanceWarningSetting () {
      this.warningBtnLoading = true;
      api_GET_ClubBalanceWarningSetting()
        .then(
          res => {
            this.warningBtnLoading = false;
            if (res) {
              this.warningData = res;
              const _vo = new BalanceWarningSettingInput();
              CopyData(res, _vo);
              this.vo = _vo;
            }
          }
        )
        .catch(
          () => {
            this.warningBtnLoading = false;
          }
        );
    },
    // 预警设置
    earlyWarningSetting () {
      if (this.warningData) {
        CopyData(this.warningData, this.vo);
      }
      this.dialogVisible = true;
    },
    // 关闭弹窗
    closeDialog () {
      this.dialogVisible = false;
    },
    // 确认提交弹窗
    submitDialog () {
      this.$refs.formBalanceWarningSetting.validate((valid) => {
        if (valid) {
          // 如果获取到了warningData表示需要修改，如果为空需要新增
          if (this.warningData) {
            this.apiEditRenewal(this.vo);
          } else {
            this.apiAddRenewal(this.vo);
          }
        }
      });
    },
    // 添加系统版本API
    apiAddRenewal (vo) {
      this.submitLoading = true;
      api_POST_ClubBalanceWarningSetting(vo)
        .then(
          res => {
            this.$message({
              message: `修改成功`,
              type: 'success',
              showClose: true
            });
            this.submitLoading = false;
            this.getClubBalanceWarningSetting();
            this.getPageList();
            this.closeDialog();
          }
        )
        .catch(
          error => {
            this.submitLoading = false;
            this.$message({
              message: `修改失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 编辑系统版本API
    apiEditRenewal (vo) {
      this.submitLoading = true;
      api_PUT_ClubBalanceWarningSetting(vo)
        .then(
          res => {
            this.$message({
              message: `修改成功`,
              type: 'success',
              showClose: true
            });
            this.submitLoading = false;
            this.getClubBalanceWarningSetting();
            this.getPageList();
            this.closeDialog();
          }
        )
        .catch(
          error => {
            this.submitLoading = false;
            this.$message({
              message: `修改失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 点击续费按钮
    clickRenewal (row) {
      console.log('clickRenewal', row);
      this.$router.push({
        name: 'Renewal',
        params: {
          studentId: row.registerStudentId,
          studentName: row.studentName
        }
      });
    },
    // 导出
    exportFile () {
      this.downloadLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '续费预警' + '.xlsx';
      api_GET_DownLoadFileAddHeader(
        tempUrl,
        fileName,
        {
          ReportName: 'StudentBalanceWarning'
        },
        WEB_CONFIG.VUE_APP_SWAGGER_HALL_BASE
      )
        .then(
          res => {
            this.downloadLoading = false;
          }
        )
        .catch(
          error => {
            this.downloadLoading = false;
            errorText(error)
              .then(
                (text) => {
                  this.$message({ type: 'error', message: text });
                }
              );
          }
        );
    },
    // 分页
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.qo.MaxResultCount = pagesize;
      this.getPageList();
    }
  }
};
</script>

<style lang="scss" scoped>
.mock_label {
  font-weight: 700;
  line-height: 36px;
}
</style>
